import { getDict } from "~/utils";
import citySelect from "../components/citySelect";
import {
	save,
	get,
	update,
	delFiles,
	validateOtherName,
	validateOtherName2,
	validatePropertyId,
	validatePropertyId2
} from "../api/other_property";
import positionDialog from "@/components/positionDialog";
import propertyList from "@/views/wy-operate/views/collection/other-property/list/property_list.vue";
import { mapGetters } from "vuex";
export default {
	components: { citySelect, positionDialog, propertyList },
	computed: {
		headers() {
			return {
				Authorization: JSON.parse(localStorage.getItem("dbl-token")).content
			};
		},
		...mapGetters({
			cityAssembly: "getCityAssembly",
			districtCollection: "getDistrictCollection"
		}),
		cityCode() {
			return this.cityAssembly.find(e => {
				if (e.value == this.propForm.otherProperty.cityCode) return e.label;
			});
		}
	},
	created() {
		this.propForm.otherProperty.cityCode = this.cityAssembly[0].value;
		this.propForm.otherProperty.countyCode = this.districtCollection[0].value;
		let routeParamId = this.$route.query.otherId;
		if (routeParamId) {
			this.isAdd = false;
			this.id = routeParamId;
			this.initCitySelector();
		}
		this.streets = getDict("streets");
		this.manageUnits = getDict("administrative_office");
		this.communityNames = getDict("community_names");
		this.landUses = getDict("land_uses");
		this.deptNames = getDict("budget_department");
	},
	data() {
		return {
			theSelectedProperty: false,
			fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
			uploadFileList: [],
			loading: true,
			isAdd: true,
			id: "",
			streets: [],
			manageUnits: [],
			provinces: [],
			citys: [],
			countys: [],
			modelType: "otherProperty",
			communityNames: [],
			communityNameStreet: [],
			landUses: [],
			deptNames: [],
			propForm: {
				otherProperty: {
					otherId: "",
					otherName: "",
					propertyId: "",
					propertyName: "",
					projectId: "",
					projectName: "",
					buildArea: "",
					manageUnit: "",
					areaCode: "",
					areaName: "",
					projectStreet: "",
					communityName: "",
					addressInfo: "",
					mapCoordinates: "",
					vrUrl: "",
					latitude: "",
					longitude: "",
					remarks: "",
					landId: "",
					parcelNum: "",
					parcelArea: "",
					landUse: "",
					landContractNum: "",
					cityCode: "",
					countyCode: "",
					street: "",
					community: "",
					landAddressInfo: "",
					address: "",
					propertyType: "",
					useType: "",
					propertyOwnership: "",
					propertyStatus: "",
					propertySource: "",
					deptId: "",
					deptName: "",
					gatherPeople: ""
				}
			},
			otherProperty_rules: {
				otherName: [
					{
						required: true,
						message: "请输入其它物业名称",
						trigger: "blur"
					},
					{
						min: 0,
						max: 30,
						message: "长度在0-30个字符串",
						trigger: "blur"
					},
					{
						validator: this.$route.query.otherId
							? this.validateOtherName2
							: this.validateOtherName,
						trigger: "blur"
					}
				],
				propertyName: [
					{
						validator: this.$route.query.otherId
							? this.validatePropertyId2
							: this.validatePropertyId,
						trigger: "change"
					}
				],
				remarks: [
					{ required: false, message: "请输入备注", trigger: "blur" },
					{
						min: 0,
						max: 333,
						message: "长度在0-333个字符串",
						trigger: "blur"
					}
				]
			}
		};
	},
	methods: {
		//   新增验证其他物业名称是否重复
		async validateOtherName(rule, value, callback) {
			let rps = await validateOtherName({
				otherName: value
			});
			if (rps.data.data == "1" && rps.data.code == "0") {
				callback(new Error("该其他物业名称已存在"));
			}
			callback();
		},
		//   修改验证其他物业名称是否重复
		async validateOtherName2(rule, value, callback) {
			let rps = await validateOtherName2({
				otherName: value,
				otherId: this.propForm.otherProperty.otherId
			});
			if (rps.data.data == "1" && rps.data.code == "0") {
				callback(new Error("该其他物业名称已存在"));
			}
			callback();
		},
		//   新增验证物业ID是否是否重复int 1存在，0 不存在
		async validatePropertyId(rule, value, callback) {
			let rps = await validatePropertyId({
				propertyId: this.propForm.otherProperty.propertyId
			});
			if (rps.data.data == "1" && rps.data.code == "0")
				callback(new Error("该物业名称已存在"));
			callback();
		},
		//  修改验证物业ID是否是否重复int 1存在，0 不存在
		async validatePropertyId2(rule, value, callback) {
			let rps = await validatePropertyId2({
				otherId: this.propForm.otherProperty.otherId,
				propertyId: this.propForm.otherProperty.propertyId
			});
			if (rps.data.data == "1" && rps.data.code == "0")
				callback(new Error("该物业名称已存在"));
			callback();
		},
		getPropertyObject(row) {
			this.theSelectedProperty = true;
			let obj = row;
			this.propForm.otherProperty = {
				...obj,
				...this.propForm.otherProperty.otherId,
				...this.propForm.otherProperty.remarks,
				...this.propForm.otherProperty.otherId
			};
			this.initCommunityName();
		},
		// 修改时初始化地址选择器
		initCitySelector() {
			const loading = this.$loading({
				lock: true,
				text: "数据加载中"
			});
			get(this.id)
				.then(rep => {
					this.isAdd = false;
					this.propForm.otherProperty = rep.data.data;
					this.propForm.otherProperty.cityCode = this.propForm.otherProperty.areaCode.split(
						"-"
					)[0];
					this.propForm.otherProperty.countyCode = this.propForm.otherProperty.areaCode.split(
						"-"
					)[1];
					this.initCommunityName();
					loading.close();
				})
				.catch(e => {
					loading.close();
					this.$message({
						type: "error",
						message: "数据获取失败!"
					});
				});
		},

		submitForm() {
			this.$refs["propForm"].validate(valid => {
				if (valid) {
					if (this.uploadFileList.length) {
						!this.isAdd
							? this.$refs.myUpload.submit(this.modelType, this.id)
							: this.$refs.myUpload.submit(this.modelType);
					} else {
						this.sendFormData();
					}
				}
			});
		},

		sendFormData(val) {
			if (val && this.isAdd) this.propForm.otherProperty.otherId = val;
			const loading = this.$loading({
				lock: true,
				text: "数据保存中"
			});
			this.propForm.otherProperty.areaCode =
				this.propForm.otherProperty.cityCode +
				"-" +
				this.propForm.otherProperty.countyCode;
			this.propForm.otherProperty.areaName =
				this.getCardTypeValue(
					this.propForm.otherProperty.cityCode,
					this.cityAssembly
				) +
				this.getCardTypeValue(
					this.propForm.otherProperty.countyCode,
					this.districtCollection
				) +
				this.getCardTypeValue(
					this.propForm.otherProperty.projectStreet,
					this.streets
				) +
				this.getCardTypeValue(
					this.propForm.otherProperty.communityName,
					this.communityNames
				);
			let areaCode =
				this.propForm.otherProperty.cityCode +
				"-" +
				this.propForm.otherProperty.countyCode +
				"-" +
				this.propForm.otherProperty.projectStreet +
				"-" +
				this.propForm.otherProperty.communityName;
			if (this.isAdd) {
				console.log(this.propForm.otherProperty);
				save(this.propForm.otherProperty)
					.then(rep => {
						loading.close();
						this.$message.success("保存成功");
						this.closeNowRouter();
					})
					.catch(e => {
						console.log(e);
						loading.close();
						this.$message.error("保存失败");
					});
			} else {
				update(this.propForm.otherProperty)
					.then(rep => {
						loading.close();
						this.$message.success("修改成功");
						this.closeNowRouter();
					})
					.catch(e => {
						console.log(e);
						loading.close();
						this.$message.error("修改失败");
					});
			}
		},

		closeNowRouter() {
			this.$router.back();
		},

		onSuccess(rep, file, fileList) {
			//文件上传成功，开始保存表单
			if (rep.data) this.sendFormData(rep.data);
			else this.err("提交失败");
		},

		handleClean(fileId) {
			this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					delFiles(fileId, this.modelType).then(resp => {
						if (resp.data.code === 0) {
							this.$message.success("删除成功!");
							this.files = this.files.filter(file => file.fileId != fileId);
						} else this.$message.error("删除失败!");
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除"
					});
				});
		},
		// 监听地图坐标监听
		resetPosition(data) {
			let position = JSON.parse(data);
			if (position.type == "location") {
				if (position.value.length) {
					this.propForm.otherProperty.mapCoordinates = position.value.join(",");
				}
				this.propForm.otherProperty.mapObject = position.mapObject
					? JSON.stringify(position.mapObject)
					: "";
			} else {
				this.propForm.otherProperty = {
					...this.propForm.otherProperty,
					fenceCoordinates: JSON.stringify(position.value)
				};
			}
		},

		// // 街道改变清空街道和社区
		handleChangeStreet() {
			this.propForm.otherProperty.addressInfo = "";
			this.propForm.otherProperty.communityName = "";
			this.initCommunityName();
		},

		// 社区改变清空详细地址
		handleChangeCommunity() {
			this.propForm.otherProperty.addressInfo = "";
		},
		//获取社区-村
		initCommunityName() {
			this.communityNameStreet.length = 0;
			let selectStreet = this.propForm.otherProperty.projectStreet;
			if (
				selectStreet &&
				this.communityNames != null &&
				this.communityNames.length
			) {
				this.communityNameStreet = this.communityNames.filter(
					cn => cn.value.indexOf(selectStreet) != -1
				);
			}
		},

		// 回显时对应value显示label
		getCardTypeValue(num, sum) {
			let arr = sum.filter(e => e.value === num);
			let result = arr.length ? arr[0].label : num;
			return result;
		}
	}
};
